﻿
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using CMN.Common;
using CMN.Entity;
using CMN.Cache;
namespace CMN.Framework
{
    public class ModuleListCache{
        private static GetModuleListCache _ModuleList = null;
         /// <summary>
        /// 构造函数
        /// </summary>
        static ModuleListCache()
        {
            _ModuleList = new GetModuleListCache();
            
        }

        /// <summary>
        ///文章缓存列表
        /// </summary>
        /// <returns>ModuleListCache实现类</returns>
        public static GetModuleListCache Instance()
        {
            return _ModuleList;
        }
    }
    
    /// <summary>
    /// 文章缓存列表缓存
    /// </summary>
    public class GetModuleListCache
    {

        //所有查询语句
       private    Dictionary<string,QueryParam> qpList;
        //所人数列表
       
        /// <summary>
        /// Cache锁
        /// </summary>
        protected ReaderWriterLock _CacheDataRwl = new ReaderWriterLock();
        //定时器
        System.Timers.Timer _UpdateTimer;
        //用户登陆超时设置(毫秒)
        double _TimeOutMilliseconds=2000;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="LoginTimeOutMinute">用户登陆超时设置(分钟)</param>
        public GetModuleListCache()
        {

            qpList = new Dictionary<string, QueryParam>();
            _UpdateTimer = new System.Timers.Timer();
            _UpdateTimer.AutoReset = true;
            _UpdateTimer.Elapsed += new System.Timers.ElapsedEventHandler(ClearTimeOutValue);
            _UpdateTimer.Interval = _TimeOutMilliseconds;
            _UpdateTimer.Start();
        }

       
        /// <summary>
        /// 清除到期在线用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClearTimeOutValue(object sender, System.Timers.ElapsedEventArgs e)
        {
            double NextRunTime = _TimeOutMilliseconds;
            DateTime _CheckTime = e.SignalTime.AddMilliseconds(_TimeOutMilliseconds * -1);
            _UpdateTimer.Stop();
            try
            {
                _CacheDataRwl.AcquireWriterLock(Timeout.Infinite);
                List<Module_ListInfo> Module_ListInfos = new List<Module_ListInfo>();
                foreach (string key in qpList.Keys)
                {
                    QueryParam qpTemp = qpList[key];
                    JsonFileCache<Module_ListInfo> jFileCache = new JsonFileCache<Module_ListInfo>();
                    //AppLog.Write(string.Concat(qpTemp.PageSize,"-size",qpTemp.PageIndex,"-index",qpTemp.ReturnFields,"--where--", qpTemp.Where,qpTemp.Orderfld,"--key--",key), AppLog.LogMessageType.Info);
                    if (jFileCache.IsOutTime(key))
                    {
                        //AppLog.Write(string.Concat("key*****", key), AppLog.LogMessageType.Info);
                        Module_ListInfos = MvcWebCacheManager.GetModuleList(qpTemp.ModuleType, qpTemp, false);
                        jFileCache.Insert(key, Module_ListInfos, qpTemp.TimeTemp, qpTemp.IsTimeSearch);
                    }
                }
                qpList.Clear();
                _UpdateTimer.Interval = NextRunTime;
            }
            catch(Exception ex)
            {
                AppLog.Write(ex.Message, AppLog.LogMessageType.Error, ex);
            }
            finally
            {
                _CacheDataRwl.ReleaseWriterLock();
            }
            _UpdateTimer.Start();
        }

       
        #region "插入用户"
        

        /// <summary>
        /// 插入用户
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void InsertValue(string key,QueryParam qp)
        {
           
           
            try
            {
                _CacheDataRwl.AcquireWriterLock(Timeout.Infinite);


                if (!qpList.ContainsKey(key))
                {

                    qpList.Add(key, qp);
                }
               
            }
            finally
            {
                _CacheDataRwl.ReleaseWriterLock();
            }
        }
        #endregion


       
        /// <summary>
        /// 根据用户名移除用户
        /// </summary>
        /// <param name="U_Name"></param>
        public void RemoveValueName(string key)
        {
            QueryParam qp;
            try
            {
                _CacheDataRwl.AcquireWriterLock(Timeout.Infinite);
                if (qpList.TryGetValue(key, out qp))
                {
                    Remove(key);
                }
            }
            finally
            {
                _CacheDataRwl.ReleaseWriterLock();
            }
        }

        /// <summary>
        /// 移除用户资料
        /// </summary>
        /// <param name="ValueNode"></param>
        private void Remove(string key)
        {

            qpList.Remove(key);
                
        }

        /// <summary>
        /// 检测Key是否在线
        /// </summary>
        /// <param name="key">用户标识</param>
        /// <returns>True在线 False不在线</returns>
        public bool CheckKeyOnline(string key)
        {
            bool rBool = false;
            try
            {
                _CacheDataRwl.AcquireReaderLock(Timeout.Infinite);
                if (qpList.ContainsKey(key))
                {
                    rBool = true;
                }
            }
            finally
            {
                _CacheDataRwl.ReleaseReaderLock();
            }
            return rBool;
        }

        

        /// <summary>
        /// 所有用户总数
        /// </summary>
        public int AllCount
        {
            get
            {
                return qpList.Count;
            }
        }

        

        /// <summary>
        /// 清除所有在线人数
        /// </summary>
        public void Clear()
        {
            _CacheDataRwl.AcquireWriterLock(Timeout.Infinite);
            
            qpList.Clear();
            
            _CacheDataRwl.ReleaseWriterLock();
        }
    }

 
}
